package org.edu.modules.logistics.base.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.edu.common.base.BasePageDto;
import org.edu.common.base.BaseServiceImpl;
import org.edu.common.utils.ConvertUtils;
import org.edu.common.base.BaseServiceImpl;
import org.edu.common.utils.ValidateUtils;
import org.edu.modules.logistics.base.mapper.VeHqBgwpflMapper;
import org.edu.modules.logistics.base.entity.VeHqBgwpfl;
import org.edu.modules.logistics.base.dto.VeHqBgwpflDto;
import org.edu.modules.logistics.base.service.VeHqBgwpflService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


/**
 * 实现类
 */
@Service
public class VeHqBgwpflServiceImpl extends BaseServiceImpl<VeHqBgwpfl, VeHqBgwpflMapper> implements VeHqBgwpflService {

    public IPage<VeHqBgwpflDto> pageDto(BasePageDto page, @Param(Constants.WRAPPER) Wrapper queryWrapper){
        return mapper.pageDto(page,queryWrapper);
    }
    /**
    * 查询实体类
    */
    public VeHqBgwpflDto findDtoById(String id) {
        VeHqBgwpfl entity = super.findById(id);
        VeHqBgwpflDto dto = ConvertUtils.convertToDto(entity, VeHqBgwpflDto.class);
        return dto;
    }

    /**
    * 新增或者修改
    */
    public void insertOrUpdate(VeHqBgwpflDto dto,Boolean isAdd){
        if(isAdd){
            super.insert(dto);
        }else{
            super.update(dto);
        }
    }

    @Override
    public void importExcel(List<Map<String, Object>> mapList) throws Exception {
        for (int i = 1; i < mapList.size(); i++) {
            Map map= mapList.get(i);
            VeHqBgwpflDto dto = new VeHqBgwpflDto();
            dto.setStatus(1);
            dto.setName((String)map.get(0));
            dto.setListSort((Integer) map.get(1));
            dto.setSfhc("否".equals( (String) map.get(2))?0:1);
            String pName = (String)map.get(3);
            if(StrUtil.isNotEmpty(pName)){
                Integer pid = findPid(pName);
                dto.setPid(pid);
                if(pid ==null){
                    throw new Exception("未找到父节点");
                }
            }
            this.insertOrUpdate(dto,true);
        }
    }
    @Override
    public Integer findPid(String name){
        LambdaQueryWrapper<VeHqBgwpfl> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(VeHqBgwpfl::getName,name);
        List<VeHqBgwpfl> veHqBgwpfls = listByWrapper(lambdaQueryWrapper);
        if(veHqBgwpfls.size()==1){
            return veHqBgwpfls.get(0).getId();
        }
        return  null;
    }

}
